package register;

import framework.URL;

import java.io.*;
import java.util.*;

public class RemoteMapRegister implements Serializable{

    public static Map<String, List<URL>> REGISTER=new HashMap<String, List<URL>>();

    public static void register(String interfaceName,URL url){
        List<URL> urls = Collections.singletonList(url);
        REGISTER.put(interfaceName,urls);
        saveFile();
    };

    public static URL random(String interfaceName){
        REGISTER=getFile();
        List<URL> list = REGISTER.get(interfaceName);
        Random random = new Random();
        int i = random.nextInt(list.size());
        return list.get(i);
    }

    public static void saveFile(){
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("/temp.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
            oos.writeObject(REGISTER);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Map<String,List<URL>> getFile(){
        try {
            FileInputStream fileInputStream = new FileInputStream("/temp.txt");
            ObjectInputStream ois = new ObjectInputStream(fileInputStream);
            return (Map<String,List<URL>>)ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
